package com.qxsx.midi.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.qxsx.midi.config.AppContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * Created by gong on 2015/7/23.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class MyNet {
    static boolean debug = true;    // debug 模式

    public static RequestQueue requestQueue;    // http 请求队列


    // 需要缓存的 消息 type
    static String[] needCacheMsgTypes = new String[]{"213", "214", "215", "216", "217", "218", "241", "243", "252", "282",
            "287", "21011", "21012", "21013", "21014", "21016", "20217"};
    // 消息 数据缓存
    static HashMap<String, JSONObject> netBack = new HashMap<String, JSONObject>();
    // 图片缓存
    static LruCache<String, Bitmap> mImageCache = new LruCache<String, Bitmap>(1000);
    // 图片缓存访问接口
    static ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
        @Override
        public Bitmap getBitmap(String s) {
            return mImageCache.get(s);
        }

        @Override
        public void putBitmap(String s, Bitmap bitmap) {
            mImageCache.put(s, bitmap);
        }
    };

    // 检查指定string 是否在 数组内
    static boolean inArray(String str, String[] array) {
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(str)) return true;
        }
        return false;
    }

    // 加载图片的处理事件
    static ImageLoader.ImageListener getMyImageListener(final ImageView view, final callBackNull callback) {
        return new ImageLoader.ImageListener() {
            public void onErrorResponse(VolleyError error) {
                callback.run();
                Log.i("get image error:", "get image error:" + error.getMessage());
            }

            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() != null) {
                    view.setImageBitmap(response.getBitmap());
                }
            }
        };
    }


    static String url = "http://121.40.139.86/VInterface/app"; // 服务器地址
    public static String baseUrl = "http://115.28.56.8/MIDI";       // 图片索引目录

    // 设置网络图片
    public static void setNetImage(final Context context, final ImageView imageView, String baseUrl) {
//        if (!imgUrl.startsWith("/")) imgUrl = '/' + imgUrl;
        final String finalImgUrl = baseUrl;

        ImageLoader mImageLoader = new ImageLoader(requestQueue, imageCache);
        ImageLoader.ImageListener listener = getMyImageListener(imageView, new callBackNull() {
            @Override
            public void run() {
                //Toast.makeText(context, "获取图片失败：" + finalImgUrl, Toast.LENGTH_SHORT).show();
            }
        });
        mImageLoader.get(baseUrl, listener);

    }

    // Post 请求
    static void doPostCallBack(JSONObject object, callBackJsonArray callback) {
        try {

            Log.i("code:", object.get("code").toString());
            Log.i("message", object.get("message").toString());
            String dataStr = object.getString("data");
            if (dataStr.equals(""))
                callback.run(object.get("code"), object.get("message"), new JSONArray());
            else {
                JSONArray array1 = object.getJSONArray("data");
                Log.i("data is:", array1.toString());
                callback.run(object.get("code"), object.get("message"), array1);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public static Activity activity;
    public static Application app;
    static boolean showedLoading = false;

//    // 显示加载的圈圈
//    static void showLoading()
//    {
//        if(dialog == null && AppContext.getContext() != null  && showedLoading == false)
//        {
//            showedLoading = true;
//            dialog = new LoadingDialog(AppContext.getContext());
//            dialog.show();
////        }
////    }
//
//    // 隐藏加载的圈圈
//    static void hideLoading()
//    {
//        if(dialog != null)
//        {
//            dialog.dismiss();
//            showedLoading = false;
//            dialog = null;
//        }
//    }

    // data 包含 type 和 data 的 array
    // callback  回调函数
    static void doPostJsonArray(JSONObject object, final callBackJsonArray callback) {
        Log.i("post send:", object.toString());
        String type = "";
        JSONObject data = object;
        try {

            type = object.getString("type");
            if (netBack.containsKey(type) && inArray(type, needCacheMsgTypes)) {
                JSONObject object1 = netBack.get(type);
                doPostCallBack(object1, callback);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        final String dataStr = encodeData(data);
        final String finalType = type;

        //showLoading();// 显示圈圈
        StringRequest sr = new StringRequest(Request.Method.POST,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("received:", response);

                        JSONObject object = decodeData(response);
                        //hideLoading();

                        if (netBack.get(finalType) != null && netBack.get(finalType).toString().equals(object.toString()))
                            return;
                        if (inArray(finalType, needCacheMsgTypes))
                            netBack.put(finalType, object);
                        doPostCallBack(object, callback);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }
        ) {
            @Override
            public byte[] getPostBody() throws AuthFailureError {
                return this.getBody();
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    Log.w("encodeData(data)",dataStr+"");

                    return dataStr.getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
        requestQueue.add(sr);
    }

    // type 功能编号
    // data 功能 jsonArray
    // callback 回调函数名


    public static void doPostJsonArray(String type, JSONArray data, final callBackJsonArray callback) {
//        JSONArray array = new JSONArray();
        if (Tools.isNetworkConnected(AppContext.getContext()) == true) {
            JSONObject object = new JSONObject();
            try {
                object.put("type", type);
                object.put("data", data);
//            array.put(object);
            } catch (JSONException e) {
                Log.i("doPost:", "Json 初始化时出错");
            }
            doPostJsonArray(object, callback);
        } else {
            Toast.makeText(AppContext.getContext(), "请检查您的网络", Toast.LENGTH_SHORT).show();
        }
    }


    // 加密数据
    static String encodeData(JSONObject object) {
        String theReturn = null;
        String str = object.toString();

        try {
            str = AesEncode.encrypt(str);
        } catch (Exception e) {
            Log.i("数据加密时出错", e.toString());
        }

        theReturn = str;

        return theReturn;
    }

    // 解密数据
    static JSONObject decodeData(String data) {
//        received:﹕ "{\"code\":500,\"message\":\"\\u63a5\\u53e3\\u7f16\\u53f7\\u4e3a\\u7a7a\",\"data\":[]}"

        try {
            // data aes 解密
            try {
                data = AesEncode.decrypt(data);
                Log.i("解出来的数据是：", data);
            } catch (Exception e) {
                Log.i("数据解密时出错:", e.toString());
            }
            JSONObject object = new JSONObject(data);

            return object;

        } catch (JSONException e) {
            Log.i("转换成jsonArray时出错：", e.toString());
        }
        return null;

    }

    // 检查 URL 如果是 http:// 直接返回，如果是服务器位置，进行转化后返回
    public static String convert2FullUrl(String url) {
        if (url.startsWith("http://")) return url;
        if (!url.startsWith("/")) url = '/' + url;
        url = MyNet.baseUrl + url;
        Log.i("url", "url" + url);
        return url;
    }
}
